<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/10/10
 * Time: 17:07
 */

namespace app\common\lib\pay;

require_once __DIR__.'/../wxpay/WxPay.Notify.php';

use app\common\model\BuyBill;
use think\Log;
use WxPayApi;
use WxPayNotify;
use WxPayOrderQuery;

class WxPayCallback extends WxPayNotify
{
    //重写回调处理函数
    public function NotifyProcess($data, &$msg)
    {

        if(!array_key_exists("transaction_id", $data)){
            $msg = "输入参数不正确";
            return false;
        }

        // 订单不存在
        $bill = BuyBill::get(['bill_no' => $data['out_trade_no']]);
        if (empty($bill)) {
            $msg = "订单不存在";
            return false;
        }

        // 金额不正确
        // todo 微信支付随机的支付奖励金导致金额核对不上，微信支付客服一口咬定是开发者的问题，无法使用这个功能
        if (round($data['total_fee']*0.01,2) != round($bill->bill_pay_amount,2)) {
//            $msg = "金额不正确";
//            return false;
            Log::error(__METHOD__.':'.json_encode($data,JSON_UNESCAPED_UNICODE));
        }

        // 订单已经完成，已支付
        if ($bill->bill_have_paid) {
            $msg = "订单已经完成";
            return true;
        }

        if ($bill->chkBought()) {
            $msg = '订单重复';
            // todo 处理重复订单的支付
            return false;
        }

        // 参数
        $bill->bill_paytime = time();
        $bill->pay_trade_no = $data['transaction_id'];

        $re = $bill->successPay();
        if ($re) return true;
        else {
            $msg = '内部错误';
            return false;
        }
    }
}